package policies

import (
	"net/http"
	"html/template"
	"regexp"

	"appengine"
	"appengine/datastore"
)


func EnableHandle(prefix string) {
	http.HandleFunc(prefix + "/", overview)
	http.HandleFunc(prefix + "/tos", tos)
	http.HandleFunc(prefix + "/privacy", privacy)
}

var validator = regexp.MustCompile("^[0-9]{14}$")
//.Format("20060102150405")

func overview(w http.ResponseWriter, r *http.Request) {
	t, err := template.ParseFiles("templates/base.html",
		"code.google.com/p/morpheus-sa/policies/templates/root.html",
		"code.google.com/p/morpheus-sa/policies/templates/overview.html")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	err = t.Execute(w, tos)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}

func tos(w http.ResponseWriter, r *http.Request) {
	t, err := template.ParseFiles("templates/base.html",
		"code.google.com/p/morpheus-sa/policies/templates/root.html",
		"code.google.com/p/morpheus-sa/policies/templates/tos.html")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	context := appengine.NewContext(r)
	query := datastore.NewQuery("TermsOfService").Order("-Enabled").Limit(1)

	var query_results []*TermsOfService
	_, err = query.GetAll(context, &query_results)

	var tos *TermsOfService
	if len(query_results) == 1{
		tos = query_results[0]
	}

	err = t.Execute(w, tos)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}

func privacy(w http.ResponseWriter, r *http.Request) {
	t, err := template.ParseFiles("templates/base.html",
		"code.google.com/p/morpheus-sa/policies/templates/root.html",
		"code.google.com/p/morpheus-sa/policies/templates/privacy.html")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	context := appengine.NewContext(r)
	query := datastore.NewQuery("PrivacyPolicy").Order("-Enabled").Limit(1)

	var query_results []*PrivacyPolicy
	_, err = query.GetAll(context, &query_results)

	var privacy *PrivacyPolicy
	if len(query_results) == 1{
		privacy = query_results[0]
	}

	err = t.Execute(w, privacy)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}
